package com.douyin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douyin.entity.ParseRecord;
import com.douyin.mapper.ParseRecordMapper;
import com.douyin.util.UserAgentUtil;
import com.douyin.util.IPLocationUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.List;
import java.util.HashMap;

@Slf4j
@Service
public class ParseRecordService extends ServiceImpl<ParseRecordMapper, ParseRecord> {
    
    @Autowired(required = false)
    private ObjectMapper objectMapper;

    public ParseRecord createParseRecord(Long userId, String originalUrl, String userIp, String userAgent, String parseSource) {
        ParseRecord record = ParseRecord.builder()
                .userId(userId)
                .originalUrl(originalUrl)
                .status(ParseRecord.STATUS_PROCESSING)
                .userIp(userIp)
                .userAgent(userAgent)
                .parseSource(parseSource != null ? parseSource : ParseRecord.SOURCE_MINIPROGRAM)
                .sourcePlatform(detectPlatformFromUrl(originalUrl))
                .retryCount(0)
                .downloadCount(0)
                .build();
        
        // 解析设备信息
        if (userAgent != null) {
            try {
                Map<String, String> deviceInfo = UserAgentUtil.parseUserAgent(userAgent);
                record.setDeviceType(deviceInfo.get("deviceType"));
                record.setBrowserName(deviceInfo.get("browserName"));
                record.setBrowserVersion(deviceInfo.get("browserVersion"));
                record.setOsName(deviceInfo.get("osName"));
                record.setOsVersion(deviceInfo.get("osVersion"));
            } catch (Exception e) {
                log.warn("解析User-Agent失败: {}", e.getMessage());
            }
        }
        
        // 解析IP地理位置
        if (userIp != null) {
            try {
                Map<String, String> locationInfo = IPLocationUtil.getLocationFromIP(userIp);
                record.setIpCountry(locationInfo.get("country"));
                record.setIpRegion(locationInfo.get("region"));
                record.setIpCity(locationInfo.get("city"));
            } catch (Exception e) {
                log.warn("解析IP地理位置失败: {}", e.getMessage());
            }
        }
        
        try {
            save(record);
        } catch (Exception e) {
            log.error("保存解析记录失败", e);
            // 创建一个临时ID用于测试
            record.setId(System.currentTimeMillis());
        }
        return record;
    }

    public void updateParseResult(Long recordId, Map<String, Object> parseResult, int parseTime) {
        try {
            ParseRecord record = getById(recordId);
            if (record == null) {
                log.warn("未找到解析记录: {}", recordId);
                return;
            }
            
            if ((Boolean) parseResult.get("success")) {
                record.setStatus(ParseRecord.STATUS_SUCCESS);
                
                // 获取解析的数据，可能在data字段中或顶层
                @SuppressWarnings("unchecked")
                Map<String, Object> data = (Map<String, Object>) parseResult.get("data");
                if (data == null) {
                    data = parseResult; // 如果没有data字段，直接使用parseResult
                }
                
                // 第三方API字段映射
                record.setVideoTitle((String) data.get("title"));
                record.setVideoCover((String) data.get("cover"));
                record.setAuthorName((String) data.get("author"));
                record.setFileType((String) data.get("fileType"));
                
                // 根据文件类型设置下载链接
                String fileType = (String) data.get("fileType");
                if ("video".equals(fileType)) {
                    String videoUrl = (String) data.get("videoUrl");
                    record.setParseResult(videoUrl);
                    log.debug("保存视频URL: {}", videoUrl);
                } else if ("image".equals(fileType)) {
                    @SuppressWarnings("unchecked")
                    java.util.List<String> images = (java.util.List<String>) data.get("images");
                    if (images != null && !images.isEmpty()) {
                        // 对于图片，保存第一张图片URL作为主要结果
                        record.setParseResult(images.get(0));
                        
                        // 将所有图片链接保存到downloadUrls字段
                        if (objectMapper != null) {
                            try {
                                Map<String, Object> imageUrls = new HashMap<>();
                                for (int i = 0; i < images.size(); i++) {
                                    imageUrls.put("image_" + (i + 1), images.get(i));
                                }
                                record.setDownloadUrls(objectMapper.writeValueAsString(imageUrls));
                            } catch (Exception e) {
                                log.warn("序列化图片链接失败: {}", e.getMessage());
                            }
                        }
                        log.debug("保存图片URLs，共{}张", images.size());
                    }
                }
                
                // 设置解析方法标识
                record.setParseMethod((String) parseResult.get("parseMethod"));
                
                log.info("✅ 解析记录更新成功: recordId={}, fileType={}, title={}", 
                    recordId, fileType, record.getVideoTitle());
            } else {
                record.setStatus(ParseRecord.STATUS_FAILED);
                record.setErrorMessage((String) parseResult.get("message"));
                record.setErrorCode((String) parseResult.get("errorCode"));
                
                // 增加重试次数
                record.setRetryCount((record.getRetryCount() != null ? record.getRetryCount() : 0) + 1);
            }
            record.setParseTime(parseTime);
            
            try {
                updateById(record);
            } catch (Exception e) {
                log.error("更新解析记录失败", e);
            }
            
        } catch (Exception e) {
            log.error("更新解析记录失败", e);
        }
    }
    
    public void recordDownload(Long recordId) {
        try {
            ParseRecord record = getById(recordId);
            if (record != null) {
                record.setDownloadCount((record.getDownloadCount() != null ? record.getDownloadCount() : 0) + 1);
                record.setLastDownloadAt(LocalDateTime.now());
                updateById(record);
            }
        } catch (Exception e) {
            log.warn("记录下载失败: {}", e.getMessage());
        }
    }

    public IPage<ParseRecord> getParseRecords(int page, int size, Long userId, Integer status, 
                                             LocalDateTime startTime, LocalDateTime endTime,
                                             String parseSource, String sourcePlatform, String deviceType) {
        Page<ParseRecord> pageParam = new Page<>(page, size);
        QueryWrapper<ParseRecord> queryWrapper = new QueryWrapper<>();
        
        if (userId != null) {
            queryWrapper.eq("user_id", userId);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        if (startTime != null) {
            queryWrapper.ge("created_at", startTime);
        }
        if (endTime != null) {
            queryWrapper.le("created_at", endTime);
        }
        if (parseSource != null) {
            queryWrapper.eq("parse_source", parseSource);
        }
        if (sourcePlatform != null) {
            queryWrapper.eq("source_platform", sourcePlatform);
        }
        if (deviceType != null) {
            queryWrapper.eq("device_type", deviceType);
        }
        
        queryWrapper.orderByDesc("created_at");
        
        try {
            return page(pageParam, queryWrapper);
        } catch (Exception e) {
            log.error("查询解析记录失败: {}", e.getMessage());
            return new Page<>(page, size);
        }
    }
    
    // 统计分析方法
    public Map<String, Object> getDetailedStatistics(LocalDateTime startTime, LocalDateTime endTime) {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            QueryWrapper<ParseRecord> baseWrapper = new QueryWrapper<>();
            
            if (startTime != null) {
                baseWrapper.ge("created_at", startTime);
            }
            if (endTime != null) {
                baseWrapper.le("created_at", endTime);
            }
            
            // 基础统计
            long totalRequests = count(baseWrapper);
            
            QueryWrapper<ParseRecord> successWrapper = new QueryWrapper<>();
            if (startTime != null) {
                successWrapper.ge("created_at", startTime);
            }
            if (endTime != null) {
                successWrapper.le("created_at", endTime);
            }
            successWrapper.eq("status", ParseRecord.STATUS_SUCCESS);
            long successRequests = count(successWrapper);
            long failedRequests = totalRequests - successRequests;
            
            stats.put("totalRequests", totalRequests);
            stats.put("successRequests", successRequests);
            stats.put("failedRequests", failedRequests);
            stats.put("successRate", totalRequests > 0 ? (double) successRequests / totalRequests : 0.0);
            
            // 按来源统计
            Map<String, Long> sourceStats = getCountByField("parse_source", baseWrapper);
            stats.put("sourceDistribution", sourceStats);
            
            // 按平台统计
            Map<String, Long> platformStats = getCountByField("source_platform", baseWrapper);
            stats.put("platformDistribution", platformStats);
            
            // 按设备类型统计
            Map<String, Long> deviceStats = getCountByField("device_type", baseWrapper);
            stats.put("deviceDistribution", deviceStats);
            
            // 按地区统计（前10）
            Map<String, Long> regionStats = getCountByField("ip_country", baseWrapper);
            stats.put("regionDistribution", regionStats);
            
        } catch (Exception e) {
            log.error("获取统计数据失败: {}", e.getMessage());
            // 返回默认统计
            stats.put("totalRequests", 0L);
            stats.put("successRequests", 0L);
            stats.put("failedRequests", 0L);
            stats.put("successRate", 0.0);
            stats.put("sourceDistribution", new HashMap<String, Long>());
            stats.put("platformDistribution", new HashMap<String, Long>());
            stats.put("deviceDistribution", new HashMap<String, Long>());
            stats.put("regionDistribution", new HashMap<String, Long>());
        }
        
        return stats;
    }
    
    public List<Map<String, Object>> getHourlyTrend(LocalDateTime startTime, LocalDateTime endTime) {
        // 这里需要在Mapper中实现SQL查询，暂时返回空列表
        return List.of();
    }
    
    public List<Map<String, Object>> getTopErrors(LocalDateTime startTime, LocalDateTime endTime, int limit) {
        // 这里需要在Mapper中实现SQL查询，暂时返回空列表
        return List.of();
    }
    
    public Map<String, Object> getPerformanceStats(LocalDateTime startTime, LocalDateTime endTime) {
        Map<String, Object> stats = new HashMap<>();
        
        QueryWrapper<ParseRecord> baseWrapper = new QueryWrapper<>();
        if (startTime != null) {
            baseWrapper.ge("created_at", startTime);
        }
        if (endTime != null) {
            baseWrapper.le("created_at", endTime);
        }
        baseWrapper.isNotNull("parse_time");
        
        // 这里需要在Mapper中实现聚合查询，暂时返回基本统计
        stats.put("avgParseTime", 0);
        stats.put("maxParseTime", 0);
        stats.put("minParseTime", 0);
        
        return stats;
    }

    private String detectPlatformFromUrl(String url) {
        if (url.contains("douyin.com")) {
            return ParseRecord.PLATFORM_DOUYIN;
        } else if (url.contains("tiktok.com")) {
            return ParseRecord.PLATFORM_TIKTOK;
        } else if (url.contains("kuaishou.com")) {
            return ParseRecord.PLATFORM_KUAISHOU;
        }
        return ParseRecord.PLATFORM_DOUYIN;
    }
    
    private Map<String, Long> getCountByField(String field, QueryWrapper<ParseRecord> baseWrapper) {
        // 这里需要在Mapper中实现GROUP BY查询，暂时返回空Map
        return new HashMap<>();
    }

    public long getTodayParseCount(Long userId) {
        try {
            QueryWrapper<ParseRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.ge("created_at", LocalDateTime.now().withHour(0).withMinute(0).withSecond(0));
            return count(queryWrapper);
        } catch (Exception e) {
            log.warn("数据库查询失败，返回默认值: {}", e.getMessage());
            return 0;
        }
    }

    public long getTotalParseCount(Long userId) {
        try {
            QueryWrapper<ParseRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("status", ParseRecord.STATUS_SUCCESS);
            return count(queryWrapper);
        } catch (Exception e) {
            log.warn("数据库查询失败，返回默认值: {}", e.getMessage());
            return 0;
        }
    }
}